<?php
class PrintorderAction extends Action {
	public function _initialize(){
		
		
		//检查认证
		$map['account'] = $this -> _post('username');
		$map['password'] = $this -> _post('password', 'md5');
		$this->siteid = $this -> _get('site_id');
		$map['status'] = array('gt', 0);
		$login = M('User') -> where($map) -> find();
		if($login){
			session(C('USER_AUTH_KEY'),$login['id']);
			if($login['isadministrator']==1){
			    session ( C ( 'ADMIN_AUTH_KEY' ), true );
		    }
			
			
			$this->suppierids = M('Supplier_user') -> Field('supplier_id') -> where(array('user_id' => session(C('USER_AUTH_KEY') ))) -> buildSql();
	    $this->is_suppierids = M('Supplier_user') -> Field('supplier_id') -> where(array('user_id' => session(C('USER_AUTH_KEY') ))) -> count();
			
		}else{
			exit('error');
		}
		$this->suppierids = M('Supplier_user') -> Field('supplier_id') -> where(array('user_id' => session(C('USER_AUTH_KEY') ))) -> buildSql();
	    $this->is_suppierids = M('Supplier_user') -> Field('supplier_id') -> where(array('user_id' => session(C('USER_AUTH_KEY') ))) -> count();
	}
	 
	
	
	
	public function order()
    {
        $info = D('Order')->where(array('id' => $this->_get('id')))->find();
        echo json_encode($info);
    }
	
	
	
	
	
	
	public function index()
    {
        $this->shippingList = M('Shipping')->where(array('site_id' => $this->siteid, 'status' => 1))->select();
        if ($this->_get('getExcel', 'int') > 0) {
            $this->getExcel = $this->_get('getExcel', 'int');
            $this->getExcel();

        }
        $pagesize = 10;


        if ($this->_get('pagesize')) {
            $pagesize = $this->_get('pagesize');
        }

        $map = "o.status = 2 and s.thtype =0 and o.site_id = " . $this->siteid;


        if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
            $map .= ' and s.supplier_id in(' . $this->suppierids . ')';
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid . ' and id in(' . $this->suppierids . ')')->select();

        } else {
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid)->select();
        }

        if (isset($_GET['supplier_id']) && intval($_GET['supplier_id']) > 0) {
            $map .= " and s.supplier_id=" . intval($_GET['supplier_id']);
            $this->assign('supplier_id', intval($_GET['supplier_id']));
        }


        if ($this->_get('shipping_id', 'int') || $this->_get('shipping_id') == '0') {
            $map .= " and o.shipping_id = " . $this->_get('shipping_id', 'int');
            $this->shipping_id = $this->_get('shipping_id');
        }
        if ($this->_get('status', 'int') || $this->_get('status') == '0') {
            $map .= " and s.status = " . $this->_get('status', 'int');
            $this->status = $this->_get('status');
        }

        /*if($this->is_suppierids > 0){
            $map .= " and s.supplier_id in(".$this->suppierids.")";
        }*/


        if ($this->_get('keywords')) {
            $map .= " and o.ordernumber like '%" . $this->_get('keywords') . "%'";
        }


        if ($this->_get('stime') || $this->_get('etime')) {

            $stime = strtotime($this->_get('stime'));
            $etime = strtotime($this->_get('etime')) + 24 * 3600;

            if ($this->_get('stime')) {
                $map .= " and o.create_time >= '" . $stime . "'";
                //$map['o.create_time'] = array('gt',$stime);
            }

            if ($this->_get('etime')) {
                $map .= " and o.create_time <= '" . $etime . "'";
            }

            if ($this->_get('etime') && $this->_get('stime')) {
                $map .= " and o.create_time <= '" . $etime . "'";
                $map .= " and o.create_time >= '" . $stime . "'";
            }

        }

        $saleDB = D('sale');
        $count = $saleDB->alias('s')->join('INNER JOIN __ORDER__ as o on o.id = s.order_id')->where($map)->getField('count(distinct(s.order_id)) as tp');

        //实例化分页类
        import('ORG.Util.Page');
        $p = new Page($count, $pagesize);

        $data = $saleDB->alias('s')->join('RIGHT JOIN __ORDER__ as o on o.id = s.order_id')->where($map)->order('create_time DESC')->group("order_id")->limit($p->firstRow . ',
' . $p->listRows) -> Field('s.*,o.ordernumber,o.shipping_status,o.tel,o.yourname,o.address,o.taxtitle') -> select();


        $memberdb = M('Member');
		
		if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
            $map .= ' and s.supplier_id in(' . $this->suppierids . ')';
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid . ' and id in(' . $this->suppierids . ')')->select();

        } else {
            $this->suppier = M('Supplier')->where('site_id=' . $this->siteid)->select();
        }
		
        foreach($data as $k => $v){
			if(!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0){
				$data[$k]['total'] = $saleDB -> where("supplier_id in(".$this->suppierids.") and order_id = '".$v['order_id']."'") -> sum('total');
			}else{
				$data[$k]['total'] = $saleDB -> where(array('order_id' => $v['order_id'])) -> sum('total');
			}
			
			$data[$k]['nickname'] = $memberdb -> where(array('id' => $v['member_id'])) -> getField('nickname');
		}


        $pages = $p->show();
       echo  json_encode($data);
    }

    public function read()
    {
            $order_id = $this->_get('id');
            $saleDB = M("Sale");
            $map = "s.order_id = '" . $order_id . "' and s.site_id = " . $this->siteid;
            if (isset($_GET['supplier_id']) && intval($_GET['supplier_id']) > 0) {
                $map .= " and s.supplier_id=" . intval($_GET['supplier_id']);
                $this->assign('supplier_id', intval($_GET['supplier_id']));
            }
            if (!session(C('ADMIN_AUTH_KEY')) && $this->is_suppierids > 0) {
                $map .= " and s.supplier_id in(" . $this->suppierids . ")";

            }
            $sale = $saleDB->alias('s')->join("left join __PRODUCT__ as p on p.id=s.product_id")->where($map)->Field('s.create_time,s.supplier_id, p.id, p.title, p.img_url, s.price, s.create_time,s.total,s.code,s.unit,s.num,s.categoryname,s.logistics_num,p.id,s.attr')->select();
            //echo $saleDB -> getLastSql();
            $attrvalDB = M('attr_val');
            foreach ($sale as $k => $v) {

                $attrval = explode(';', $v['attr']);
                $sale[$k]['attrmes'] = array();

                foreach ($attrval as $v) {
                    $mes = $attrvalDB->where(array('id' => $v))->find();
                    array_push($sale[$k]['attrmes'], $mes['val']);
                }
            }

            echo json_encode($sale);
            //$this->display();
    }
	
	//订单发货
	public function logistics(){
	   $order_id = $this->_post('order_id');
	   $logistics_num = $this->_post('logistics_num');
	   //更新物流单号
	   $orderDB = D('Order');
	   $saleDB = M('sale');
	   $memberDB = M('member');
	   //判断是否支付
	   $order = $orderDB->where(array('id'=>$order_id))->find();
	   
	   if($order['status'] != 2){
		   
	     $this->error("订单尚未支付");exit;
	   }
	   $map = array(
		  'order_id' => $order_id
		 
		);
		
		if($this->is_suppierids > 0){
			$map['supplier_id'] = array('in', $this->suppierids);
		}
	   $mes = $saleDB->where($map)->save(array('logistics_num'=>$logistics_num,'status'=>1));
	   $orderDB -> updateshipping($order_id);
	   //更新订单状态
	   
	   if($mes){
		   //推送状态
		   $member = $memberDB->where(array('id'=>$order['member_id']))->find();
		   $mes = "您的订单".$order['ordernumber']."已经发货，请到个人中心查询";
		   sendWXMsg($member['openid'],$mes);
		   $this->success("发货成功");
		}else{
		  $this->error("更新订单失败");
		}
	}
	
	
	//登录后读取数据
	public function getShippingList(){
		$ret = D('Shipping') -> where(array('status' => 1, 'site_id' => $this->_post('site_id'))) -> Field("id,title") -> select();
		//exit(D('Shipping') -> getLastSql());
		exit(json_encode($ret));
	}
	
	public function getSiteList(){
		if(session(C('ADMIN_AUTH_KEY'))){
			exit(json_encode(D('Site') -> where(array('status' => 1)) -> Field("id,title") -> select()));
		}
		echo json_encode(D('User') -> getSiteList(session(C('USER_AUTH_KEY') )));
	}
	//返回一个快递单视图
	public function getShippingView(){
		echo M('Shipping') -> where(array('id' => $this->_post('shipping_id'))) -> getField('template');
	}
	
	
	
	
	public function getNext(){
		
		$map = array();
		if($this->_request('id', 'int') > 0){
			$map['o.id'] = array('lt', $this->_request('id', 'int'));
		}
		$saleDB = M("Sale"); 
		if($this->is_suppierids > 0){
			$map['s.supplier_id'] = array('in', $this->suppierids);
		}
		$data = $saleDB->alias('s')->join('RIGHT JOIN __ORDER__ as o on o.id = s.order_id')->where($map)->order('create_time DESC')->group("order_id") ->limit('1') -> getField('o.id');
		echo $data;
	}
	
	//返加发货单 
	public function getSaleList(){
		$order_id = $this->_request('id');
		$saleDB = M("Sale"); 
		
		
		
		
		$map=array('s.order_id'=>$order_id);
		if($this->is_suppierids > 0){
			$map['s.supplier_id'] = array('in', $this->suppierids);
		}
		
		$sale = $saleDB->alias('s')->join("left join __PRODUCT__ as p on p.id=s.product_id")->where($map)->select();
		$attrvalDB = M('attr_val');
		foreach($sale as $k=>$v){
		   
		   $attrval = explode(';',$v['attr']);
		   $sale[$k]['attrmes'] = array();
		   
		   foreach($attrval as $v){ 
		     $mes = $attrvalDB->where(array('id'=>$v))->find();
			 array_push($sale[$k]['attrmes'],$mes['val']);
		   }
		   
		}
        $this->assign('list',$sale);
		$this->display();
	}
	 
}
